package davion.study.summercloud.service;

import davion.study.summercloud.mapper.FileFolderMapper;
import davion.study.summercloud.mapper.FileStoreMapper;
import davion.study.summercloud.mapper.MyFileExtMapper;
import davion.study.summercloud.model.*;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author: Davion
 * @date: 2020/6/16
 * @description:
 */
@Service
public class FileStoreService {

    @Resource
    FileStoreMapper fileStoreMapper;

    @Resource
    MyFileExtMapper myFileExtMapper;

    @Resource
    FileFolderMapper fileFolderMapper;

    public Boolean insert(FileStore fileStore) {
        return fileStoreMapper.insert(fileStore) != 0;
    }

    public FileStoreStatistics getCountStatistics(Integer userId) {
        FileStoreExample example = new FileStoreExample();
        example.createCriteria()
                .andUserIdEqualTo(userId);
        List<FileStore> fileStores = fileStoreMapper.selectByExample(example);
        FileStore fileStore = fileStores.get(0);
        FileStoreStatistics countStatics = myFileExtMapper.getCountStatics(fileStore.getId());
        countStatics.setFileStore(fileStore);
        FileFolderExample folderExample = new FileFolderExample();
        folderExample.createCriteria()
                .andStoreIdEqualTo(fileStore.getId());
        countStatics.setFolderCount((int) fileFolderMapper.countByExample(folderExample));
        return countStatics;
    }


    public FileStore getStoreByUserId(Integer userId) {
        FileStoreExample storeExample = new FileStoreExample();
        storeExample.createCriteria()
                .andUserIdEqualTo(userId);
        List<FileStore> fileStores = fileStoreMapper.selectByExample(storeExample);
        if (fileStores.size() == 0){
            return null;
        }
        return fileStores.get(0);
    }

    public Boolean addStoreSize(FileStore fileStore, Integer addSize) {
        fileStore.setCurrentSize(fileStore.getCurrentSize() + addSize);
        return fileStoreMapper.updateByPrimaryKey(fileStore) == 1;
    }

    public Boolean subStoreSize(Integer storeId, Integer subSize) {
        FileStore fileStore = fileStoreMapper.selectByPrimaryKey(storeId);
        fileStore.setCurrentSize(fileStore.getCurrentSize() - subSize);
        return fileStoreMapper.updateByPrimaryKey(fileStore) == 1;
    }
}
